package pri.jz.keeper.ui.main

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import pri.jz.keeper.R
import pri.jz.keeper.db.AppDatabase
import pri.jz.keeper.ui.base.BaseViewModel
import pri.jz.keeper.repository.UserRepository
import pri.jz.keeper.util.NetworkUtil
import pri.jz.keeper.webservice.WebService
import pri.jz.keeper.webservice.retrofit.UserService

/**
 *Author by: JZ
 *Email: 2451756617@qq.com
 *PS:
 */
class MainViewModel(private var application: Application) : BaseViewModel(application) {
    private val _mainUiState = MutableStateFlow<MainUiState>(MainUiState.DEFAULT)
    var mainUiState = _mainUiState.asStateFlow()

    private val userRepository =  UserRepository.getIns(
        AppDatabase.getIns(application).userDao(),
        WebService.retrofitClient.create(UserService::class.java)
    )

    fun setMainUiState(uiState: MainUiState) {
        _mainUiState.update {
            uiState
        }
    }

    fun initData() {
        viewModelScope.launch(Dispatchers.IO) {
            var id = -111
            launch {
                delay(2000)
                if (id != -111) {
                    startState(id)
                    userRepository.userId = id
                } else {
                    setMainUiState(MainUiState.EXIT)
                }
            }
            launch {
                application.getSharedPreferences(
                    application.getString(R.string.shard_table_name_user), Context.MODE_PRIVATE
                ).getInt(application.getString(R.string.shard_table_user_id),-1).also {userId ->
                    id = userId
                    NetworkUtil.registerNetworkCallback(application)
                }
            }
        }
    }

    /**
     * 根据用户状态启动相应Activity
     * @param context
     * @param userId
     */
    private suspend fun startState(userId: Int) = withContext(Dispatchers.Main) {
        if (userId == -1) {
            setMainUiState(MainUiState.LOGIN)
        }else {
            setMainUiState(MainUiState.CONTENT(userId))
        }
    }

}